<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="用户组名称" prop="groupId" label-width="auto">
        <el-select
          @change="groupSelect"
          v-model="queryParams.groupId"
          placeholder="请选择用户组"
          clearable
          class="!w-240px"
        >
          <el-option v-for="item in groupList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="仓库名称" prop="projectId" v-if="showProject">
        <el-select
          v-model="queryParams.projectId"
          placeholder="请选择仓库"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="item in projectList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="提交时间" prop="commitTime">
        <el-date-picker
          v-model="queryParams.commitTime"
          type="daterange"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
          unlink-panels
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery"> <Icon icon="ep:refresh" />重置 </el-button>
        <el-button @click="getList"> 刷新 </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column
        align="center"
        label="提交ID"
        prop="commitId"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        align="center"
        label="用户组名称"
        prop="groupName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        align="center"
        label="仓库名称"
        prop="projectName"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <div
            @click="handleProjectNameClick(scope.row, false)"
            style="color: #0560fd; cursor: pointer"
          >
            {{ scope.row.projectName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="提交时间" prop="commitTime" min-width="100px" />
      <el-table-column
        align="center"
        label="提交人"
        prop="commitPerson"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        align="center"
        label="提交信息"
        prop="commitMessage"
        min-width="100px"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        align="center"
        label="分支"
        prop="branchName"
        :show-overflow-tooltip="true"
      />
      <el-table-column prop="scStatus" label="静态检查" align="center">
        <template #default="scope">
          <div @click="openForm('StaticTest', scope.row)">
            <el-button
              link
              type="success"
              :icon="CircleCheck"
              v-show="scope.row.scStatus == 'SUCCESS' || scope.row.scStatus == 'FAILURE'"
            >
              完成
            </el-button>
          </div>
          <el-button
            link
            type="primary"
            :icon="Loading"
            loading
            v-show="scope.row.scStatus == 'WAIT'"
          >
            等待
          </el-button>
          <el-button link type="info" :icon="Remove" v-show="scope.row.scStatus == 'LOCK'">
            禁用
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="unitTest" label="单元测试" align="center">
        <template #default="scope">
          <div @click="openForm('UnitTest', scope.row)">
            <el-button
              link
              type="success"
              :icon="CircleCheck"
              v-show="scope.row.unitTest == 'SUCCESS' || scope.row.unitTest == 'FAILURE'"
            >
              完成
            </el-button>
          </div>
          <el-button
            link
            type="primary"
            :icon="Loading"
            loading
            v-show="scope.row.unitTest == 'WAIT'"
          >
            等待
          </el-button>
          <el-button link type="info" :icon="Remove" v-show="scope.row.unitTest == 'LOCK'">
            禁用
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="crStatus" label="提交详情" align="center">
        <template #default="scope">
          <router-link :to="{ name: 'CrStatus', query: { params: JSON.stringify(scope.row) } }">
            <el-button link type="primary" :icon="View"> 查看 </el-button>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column prop="deployStatus" label="产品部署" align="center">
        <template #default="scope">
          <div @click="openForm('DeployStatus', scope.row)">
            <el-button
              link
              type="success"
              :icon="CircleCheck"
              v-show="scope.row.deployStatus == 'SUCCESS' || scope.row.deployStatus == 'FAILURE'"
            >
              完成
            </el-button>
          </div>
          <el-button
            link
            type="primary"
            :icon="Loading"
            loading
            v-show="scope.row.deployStatus == 'WAIT'"
          >
            等待
          </el-button>
          <el-button link type="info" :icon="Remove" v-show="scope.row.deployStatus == 'LOCK'">
            禁用
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
  <!-- 表单弹窗：静态检查/单元测试/产品部署 -->
  <ciForm ref="formRef" />
</template>
<script lang="ts" setup>
defineOptions({ name: 'SystemRole' })
import { CircleCheck, Remove, Loading, View } from '@element-plus/icons-vue'
import * as CiApi from '@/api/system/ci'
import ciForm from './ciForm.vue'
import { getUserId, getTenantId } from '@/utils/auth'

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([{}]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  groupId: null,
  projectId: null,
  commitTime: '',
  userId: null,
  tenantId: null
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
let ws: WebSocket | null = null
const userId = getUserId()
if (userId === 1 || userId === 252 || userId == 266) {
  // 指定用户，建立 WebSocket 连接
  ws = new WebSocket(import.meta.env.VITE_WS_URL)
} else {
  // 暂无数据
  list.value = []
  loading.value = false
}
if (ws) {
  ws.onopen = function () {
    //当WebSocket创建成功时，触发onopen事件
    queryParams.userId = getUserId()
    queryParams.tenantId = getTenantId()
    //将消息发送到服务端
    ws?.send(JSON.stringify(queryParams))
  }
}
const getList = async () => {
  if (!ws) return
  if (ws.readyState === ws.OPEN) {
    // 已建立成功 直接发送消息
    ws.send(JSON.stringify(queryParams))
  }
  ws.onmessage = function (e) {
    //当客户端收到服务端发来的消息时，触发onmessage事件，参数e.data包含server传递过来的数据
    let data = JSON.parse(e.data)
    list.value = data.records
    total.value = data.total
    loading.value = false
  }
  ws.onerror = function (e) {
    //如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
    console.log(e)
  }
  // loading.value = true
  // try {
  //   const data = await CiApi.getCiPage(queryParams)
  //   list.value = data.records
  //   total.value = data.total
  // } finally {
  //   loading.value = false
  // }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  showProject.value = false
  handleQuery()
}

/** 静态检查/单元测试/产品部署操作 */
const formRef = ref()
const openForm = (type: string, row?: any) => {
  formRef.value.open(type, row)
}

const groupList = ref([]) //用户组列表
const getGroup = async () => {
  const data = await CiApi.getGroupList()
  groupList.value = data
}

const showProject = ref(false)
/** 选择用户组名称，查询仓库名称 */
const groupSelect = (row) => {
  queryParams.projectId = null
  projectList.value = []
  if (row == undefined) {
    queryParams.groupId = null
    showProject.value = false
  } else {
    getProject(queryParams.groupId)
    showProject.value = true
  }
}
const projectList = ref([]) //仓库列表
const getProject = async (row) => {
  let params = { groupId: row }
  const data = await CiApi.getProjectList(params)
  projectList.value = data
}

/** 使用 setInterval 每10秒刷新一次列表 */
// const intervalId = setInterval(() => {
//   getList()
// }, 10000);

const handleProjectNameClick = (row, flag) => {
  formRef.value.click(row, flag)
}

/** 清除定时器 **/
// onUnmounted(() => {
//   clearInterval(intervalId);
// });

/** 初始化 **/
onMounted(() => {
  getList()
  getGroup()
})
</script>
